<?php
// 独立安装程序后端
// 不依赖任何框架，纯PHP实现

// 设置CORS头，允许前端访问
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');

// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 获取ThinkPHP项目根目录路径（从public/install目录向上两级）
$rootPath = dirname(dirname(__DIR__)) . '/';

// 安装锁文件路径
$lockFilePath = $rootPath . '/install.lock';

// 如果已经安装，禁止访问
if (file_exists($lockFilePath)) {
    echo json_encode(['code' => 0, 'message' => '系统已经安装，请勿重复操作！']);
    exit();
}

// 获取请求的action
$action = $_POST['action'] ?? '';

switch ($action) {
    case 'checkEnv':
        checkEnv($rootPath);
        break;
    case 'checkDb':
        checkDb();
        break;
    case 'executeInstall':
        executeInstall($rootPath);
        break;
    default:
        echo json_encode(['code' => 0, 'message' => '无效的操作']);
        break;
}

/**
 * 检查环境
 */
function checkEnv($rootPath) {

    $checks = [
        'php_version' => [
            'name' => 'PHP 版本',
            'required' => '>= 8.1',
            'current' => PHP_VERSION,
            'pass' => version_compare(PHP_VERSION, '8.1.0', '>=')
        ],
        'fileinfo' => [
            'name' => 'fileinfo 扩展',
            'required' => '已安装',
            'current' => extension_loaded('fileinfo') ? '已安装' : '未安装',
            'pass' => extension_loaded('fileinfo')
        ],
        'pdo_mysql' => [
            'name' => 'PDO MySQL 扩展',
            'required' => '已安装',
            'current' => extension_loaded('pdo_mysql') ? '已安装' : '未安装',
            'pass' => extension_loaded('pdo_mysql')
        ],
        'data_sql' => [
            'name' => 'data.sql 文件',
            'required' => '存在',
            'current' => file_exists($rootPath . '/data.sql') ? '存在' : '不存在',
            'pass' => file_exists($rootPath . '/data.sql')
        ],
        'vue_node_modules' => [
            'name' => '前端依赖',
            'required' => '可完成向导后安装',
            'current' => file_exists($rootPath . '/ui/node_modules') ? '存在' : '不存在',
            'pass' => true
        ]
    ];

    echo json_encode(['code' => 1, 'data' => $checks]);
}

/**
 * 检查数据库连接
 */
function checkDb() {
    $dbHost = $_POST['db_host'] ?? '';
    $dbPort = $_POST['db_port'] ?? '';
    $dbUser = $_POST['db_user'] ?? '';
    $dbPass = $_POST['db_pass'] ?? '';
    $dbName = $_POST['db_name'] ?? '';

    if (empty($dbHost) || empty($dbPort) || empty($dbUser) || empty($dbName)) {
        echo json_encode(['code' => 0, 'message' => '数据库信息不完整！']);
        return;
    }

    try {
        // 1. 不指定数据库名，连接MySQL服务
        $dsn = "mysql:host={$dbHost};port={$dbPort};charset=utf8mb4";
        $pdo = new PDO($dsn, $dbUser, $dbPass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);

        // 2. 检查MySQL版本
        $stmt = $pdo->query('SELECT VERSION() as version');
        $result = $stmt->fetch();
        $version = $result['version'];
        
        if (version_compare($version, '8.0.0', '<')) {
            echo json_encode(['code' => 0, 'message' => 'MySQL版本需要 >= 8.0，当前版本为 ' . $version]);
            return;
        }

        // 3. 尝试创建数据库
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

        // 4. 将有效的数据库配置保存到临时文件
        $dbConfig = [
            'db_host' => $dbHost,
            'db_port' => $dbPort,
            'db_user' => $dbUser,
            'db_pass' => $dbPass,
            'db_name' => $dbName
        ];
        file_put_contents(__DIR__ . '/temp_db_config.json', json_encode($dbConfig));

        echo json_encode(['code' => 1, 'message' => '数据库连接成功，数据库已创建！']);

    } catch (PDOException $e) {
        echo json_encode(['code' => 0, 'message' => '数据库连接失败：' . $e->getMessage()]);
    }
}

/**
 * 执行安装
 */
function executeInstall($rootPath) {
    $adminUser = $_POST['admin_user'] ?? '';
    $adminPass = $_POST['admin_pass'] ?? '';

    if (strlen($adminUser) < 6 || strlen($adminPass) < 6 ) {
        echo json_encode(['code' => 0, 'message' => '输入的用户名和密码必须是6位以上字符串！']);
        return;
    }

    if (empty($adminUser) || empty($adminPass)) {
        echo json_encode(['code' => 0, 'message' => '管理员信息不完整！']);
        return;
    }

    // 从临时文件中获取数据库配置
    $tempConfigFile = __DIR__ . '/temp_db_config.json';
    if (!file_exists($tempConfigFile)) {
        echo json_encode(['code' => 0, 'message' => '数据库配置已过期，请返回上一步重新配置。']);
        return;
    }

    $dbConfig = json_decode(file_get_contents($tempConfigFile), true);
    if (!$dbConfig) {
        echo json_encode(['code' => 0, 'message' => '数据库配置读取失败。']);
        return;
    }

    try {
        // 连接到指定数据库
        $dsn = "mysql:host={$dbConfig['db_host']};port={$dbConfig['db_port']};dbname={$dbConfig['db_name']};charset=utf8mb4";
        $pdo = new PDO($dsn, $dbConfig['db_user'], $dbConfig['db_pass'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);

        // 1. 导入 data.sql
        $sqlFilePath = $rootPath . '/data.sql';
        if (!file_exists($sqlFilePath)) {
            echo json_encode(['code' => 0, 'message' => 'data.sql 文件不存在！']);
            return;
        }

        $sqlContent = file_get_contents($sqlFilePath);
        // 分割SQL语句并执行
        $sqlStatements = explode(";\n", str_replace("\r", "\n", $sqlContent));
        foreach ($sqlStatements as $sql) {
            $sql = trim($sql);
            if (!empty($sql)) {
                $pdo->exec($sql);
            }
        }

        // 2. 生成管理员密码哈希
        $jwtSecret= strtoupper(bin2hex(random_bytes(32)));
        $join = $adminUser . $adminPass;
        $joinHash = password_hash($join, PASSWORD_DEFAULT);
        // 3. 创建 .env 配置文件
        $envContent = <<<EOT
APP_DEBUG=true

DB_TYPE=mysql
DB_HOST={$dbConfig['db_host']}
DB_NAME={$dbConfig['db_name']}
DB_USER={$dbConfig['db_user']}
DB_PASS={$dbConfig['db_pass']}
DB_PORT={$dbConfig['db_port']}
DB_CHARSET=utf8mb4
DB_PREFIX=ra_

DEFAULT_LANG=zh-cn

JWT_SECRET={$jwtSecret}
SUPER_HASH={$joinHash}
EOT;
        file_put_contents($rootPath . '/.env', $envContent);

        // 4. 创建安装锁文件
        file_put_contents($rootPath . '/install.lock', 'installed at ' . date('Y-m-d H:i:s'));

        // 5. 自动生成 前端配置文件 .env.development
        $protocol = (!empty($_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $base_api = $protocol . $_SERVER['HTTP_HOST'];
        $content = <<<EOT
# 代理模式的后端服务器地址
VITE_APP_BASE_API={$base_api}

# 百度地图
VITE_APP_MAP_BMAP_AK=

# 高德地图密钥
VITE_APP_MAP_AMAP_KEY=
VITE_APP_MAP_AMAP_SECRET=

# 腾讯地图密钥
VITE_APP_MAP_TMAP_AK=

EOT;
        file_put_contents($rootPath . '/ui/.env.development', $content);

        // 6. 清理临时文件
        if (file_exists($tempConfigFile)) {
            unlink($tempConfigFile);
        }


        echo json_encode(['code' => 1, 'message' => '恭喜您，系统安装成功！']);

    } catch (PDOException $e) {
        echo json_encode(['code' => 0, 'message' => '安装失败：' . $e->getMessage()]);
    } catch (Exception $e) {
        echo json_encode(['code' => 0, 'message' => '安装失败：' . $e->getMessage()]);
    }
}
?>
